<?php

namespace app\api\controller;

use app\api\model\Banners;
use app\api\model\Coupons;
use app\api\model\UserCoupons;
use app\common\controller\Api;
use Endroid\QrCode\Response\QrCodeResponse;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['banner', 'info'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function banner()
    {
        $banners = Banners::getBanners();
        $banners ? $this->success('请求成功', ['banners' => $banners]) : $this->error('没有数据');
    }

    /**
     * 基本信息
     */
    public function info()
    {
        $service_time = getSetting(config('setting.service_time'));
        $address = getSetting(config('setting.address'));
        $store_name = getSetting(config('setting.store_name'));
        $this->success('请求成功', [
            'service_time' => $service_time,
            'address' => $address,
            'store_name' => $store_name
        ]);
    }

    /**
     * 优惠券
     */
    public function coupon()
    {
        $coupons = Coupons::getCoupons();
        if (!$coupons) {
            $this->error('暂无优惠券', [], 2);
        }
        $user_id = $this->auth->getUserId();
        foreach ($coupons as $val) {
            //未领取
            $is_get = 0;
            if ($user_id) {
                $user_coupon = UserCoupons::getUserCoupon($user_id, $val->id);
                if ($user_coupon) {
                    //已领取
                    $is_get = 1;
                }
            }
            $val->is_get = $is_get;
        }
        $this->success('请求成功', ['coupons' => $coupons]);
    }

    /**
     * 领取优惠券
     */
    public function getCoupon($coupon_id)
    {
        $coupon = Coupons::find($coupon_id);
        if (!$coupon) {
            $this->error('优惠券无效，请稍后再领取');
        }
        $user_coupon = UserCoupons::getUserCoupon($this->auth->getUserId(), $coupon_id);
        if ($user_coupon) {
            $this->error('此优惠券已被领取');
        }
        $result = UserCoupons::createUserCoupon($this->auth->getUserId(), $coupon);
        if (!$result) {
            $this->error('领取失败');
        }
        $this->success('领取成功');
    }

}
